<template>
  <div class="">
    <div class="boardCalendarBox">
      <!-- 选择月份 -->
      <div class="selectDateBox">
        <div class="left" @click="previousDate">
          <a-icon type="left" />
        </div>
        <div class="content">
          <span>{{ currentTime }}</span>
        </div>
        <div class="right">
          <a-icon type="right" @click="nextDate" />
        </div>
      </div>
      <!-- 星期几 -->
      <div class="weekheadBox">
        <div class="dayBox" v-for="(day, index) in weekHeader" :key="index">
          <span>{{ day }}</span>
        </div>
      </div>
      <!-- 日历主体 -->
      <div class="weekBodyBox">
        <div class="weekBox" v-for="(week, weekIndex) in calendarDateLists" :key="weekIndex">
          <div class="dayBox" @click="getDayPlan(day, dayIndex, weekIndex)" :class="{ currentDay: day.isCurrentDay }" v-for="(day, dayIndex) in week" :key="dayIndex">
            <span>{{ day.name }}</span>
            <div class="hasPlan" v-show="day.hasPlan">
              <a-icon type="star" theme="filled" />
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="infoBox">
      <swiper class="swiper-container" ref="mySwiper" :options="swiperOptions">
        <swiperSlide class="swiper-wrapper" v-for="(item, index) in dayOfPlanLists" :key="index">
          <div class="itemBox">
            <div class="headBox">
              <div class="left">
                <span>{{ item.shiftName }}</span>
              </div>
              <div class="right"><span>详情></span></div>
            </div>
            <div class="bodyBox">
              <div class="contentBox">
                <span class="label">上班时间</span><span class="text">{{ item.planTime }}</span>
              </div>
              <div class="contentBox">
                <span class="label">产出件数</span><span class="text">{{ item.produceNum }}</span>
              </div>
            </div>
          </div>
        </swiperSlide>
        <!-- Add Pagination -->
        <div class="swiper-pagination" slot="pagination"></div>
        <!-- Add Arrows -->
        <!-- <div class="swiper-button-prev" slot="button-prev"></div> -->
        <!-- <div class="swiper-button-next" slot="button-next"></div> -->
      </swiper>
    </div>
  </div>
</template>

<script>
import moment from 'moment';
import { swiper, swiperSlide } from 'vue-awesome-swiper';
import 'swiper/dist/css/swiper.css';
import api from '@api/api';
import { getRoleId, buildDateAxis, isString } from '@/unit/tool';
// import { RepairType } from '@/unit/constantValue';
import '@assets/styles/publicStyle/index.less';

import { createNamespacedHelpers } from 'vuex';
const { mapState } = createNamespacedHelpers('board/');

const weekHeader = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];

function buildMonth(parames) {
  let { startTime, endTime, hasPlanlists, currentTime } = parames;

  let timeFormat = 'days';

  // 计算指定日期的周一日期
  let firstWeekMonthOfday = moment(startTime, 'YYYY-MM-DD').format('E');
  let endWeekMonthOfday = moment(endTime, 'YYYY-MM-DD').format('E');

  let monthDays = buildDateAxis({ startTime, endTime, timeFormat });

  for (let index = 0; index < firstWeekMonthOfday - 1; index++) {
    monthDays.unshift('');
  }

  for (let index = 0; index < 7 - endWeekMonthOfday; index++) {
    monthDays.push('');
  }

  let _monthDays = monthDays.map((item, index) => {
    return {
      name: formatDate(item),
      value: item,
      disabled: item ? true : false,
      hasPlan: false,
      isCurrentDay: item == currentTime ? true : false,
    };
  });

  console.log(_monthDays);

  hasPlanlists.forEach((item, i) => {
    _monthDays.forEach((day, j) => {
      if (item == day.value) {
        day.hasPlan = true;
      }
    });
  });

  let list = [];
  for (let i = 0; i < _monthDays.length; i += 7) {
    list.push(_monthDays.slice(i, i + 7));
  }

  return list;
}

function formatDate(str) {
  if (isString(str)) {
    let index = str.lastIndexOf('\-');
    str = str.substring(index + 1, str.length);
    return parseInt(str).toString();
  } else {
    return '';
  }
}

function formatPlanLists(lists) {
  return lists.map((item, index) => {
    let { startTime, startStamp, endTime, endStamp, produceCount, ...rest } = item;

    // let st = moment(startStamp).format('YYYY-MM-DD HH:mm:ss');
    // let et = moment(endStamp).format('YYYY-MM-DD HH:mm:ss');
    let currentTime = `${item.day} ${moment().format('HH:mm:ss')}`;
    let isCurrentPlan = moment(currentTime).isBetween(startStamp, endStamp);
    // debugger;
    return {
      planTime: `${formatPanTime(startTime)} - ${formatPanTime(endTime)}`,
      produceNum: `${produceCount} 件`,
      isCurrentPlan,
      ...item,
    };
  });
}

function formatPanTime(str) {
  return str
    .split(':')
    .slice(0, -1)
    .join(':');
}

export default {
  name: 'boardCalendar',
  components: {
    // NormalPie,
    swiper,
    swiperSlide,
  },
  props: {},
  data() {
    return {
      userName: '',
      name: '',
      role: '',
      compId: '',
      pieData: {},
      weekHeader,
      calendarDateLists: [],
      startTime: moment()
        .startOf('month')
        .format('YYYY-MM-DD'),
      endTime: moment()
        .endOf('month')
        .format('YYYY-MM-DD'),
      currentTime: moment().format('YYYY-MM-DD'),
      swiperOptions: {
        slidesPerView: 3,
        // spaceBetween: 6,
        // navigation: {
        //   nextEl: '.swiper-button-next',
        //   prevEl: '.swiper-button-prev',
        // },
        // pagination: {
        //   el: '.swiper-pagination',
        //   type: 'bullets',
        // },
      },
      dayOfPlanLists: [],
    };
  },
  watch: {
    timeSwich: function(newValue, oldValue) {
      let { startTime, endTime } = newValue;
    },
  },
  computed: {
    ...mapState(['timeSwich']),
    // swiper() {
    //   return this.$refs.mySwiper.$swiper;
    // },
    swiper() {
      //实例swiper对象
      return this.$refs.mySwiper.swiper;
    },
  },
  methods: {
    // 计算本月时间
    buildCalendarDate(key) {
      // let let;
      // this[key] = buildMonth({ startTime, endTime });
      // console.log(this[key]);
    },

    previousDate() {
      this.currentTime = moment()
        .month(moment(this.currentTime).month() - 1)
        .format('YYYY-MM-DD');
      this.startTime = moment()
        .month(moment(this.currentTime).month())
        .startOf('month')
        .format('YYYY-MM-DD');
      this.endTime = moment()
        .month(moment(this.currentTime).month())
        .endOf('month')
        .format('YYYY-MM-DD');

      this.boardGetAllDay('calendarDateLists');
    },

    nextDate() {
      this.currentTime = moment()
        .month(moment(this.currentTime).month() + 1)
        .format('YYYY-MM-DD');
      this.startTime = moment()
        .month(moment(this.currentTime).month())
        .startOf('month')
        .format('YYYY-MM-DD');
      this.endTime = moment()
        .month(moment(this.currentTime).month())
        .endOf('month')
        .format('YYYY-MM-DD');

      this.boardGetAllDay('calendarDateLists');
    },

    getDayPlan(item, dayIndex, weekIndex) {
      let _this = this;
      this.calendarDateLists = dayHandle(item, dayIndex, weekIndex);

      this.boardGetShiftByDay(item.value, 'dayOfPlanLists');

      function dayHandle(day, dayIndex, weekIndex) {
        let lists = _this.calendarDateLists;

        _this.calendarDateLists.forEach((week, wIndex) => {
          week.forEach((day, dIndex) => {
            if (wIndex == weekIndex && dIndex == dayIndex) {
              day.isCurrentDay = true;
            } else {
              day.isCurrentDay = false;
            }
          });
        });

        return lists;
      }
    },

    // 获取班次日历数据
    async boardGetAllDay(key) {
      const resData = await api.boardGetAllDay({ companyId: this.compId, startTime: this.startTime, endTime: this.endTime });
      let hasPlanlists = resData;
      this[key] = buildMonth({ startTime: this.startTime, endTime: this.endTime, currentTime: this.currentTime, hasPlanlists });
    },

    // 根据日期获取当天的班次及打卡情况
    async boardGetShiftByDay(day, key) {
      const resData = await api.boardGetShiftByDay({ companyId: this.compId, username: this.userName, day });
      let planLists = formatPlanLists(resData);

      let currentPlanIndex = planLists.findIndex((item) => item.isCurrentPlan);
      this[key] = formatPlanLists(resData);

      if (currentPlanIndex > 2) {
        this.swiper.slideTo(currentPlanIndex - 1, 1000, false);
      }
    },
  },
  created() {},
  mounted() {
    getRoleId(this);
    this.boardGetAllDay('calendarDateLists');
    this.boardGetShiftByDay(this.currentTime, 'dayOfPlanLists');
  },
};
</script>

<style scoped="scoped" lang="less">
@import './style.less';
</style>
